package com.hunlian.makelove.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hunlian.makelove.AppApplication;
import com.hunlian.makelove.R;
import com.hunlian.makelove.TakeCameraOrAlbum;
import com.hunlian.makelove.bean.OrganizingDataBean;
import com.hunlian.makelove.clipimage.ClipImageActivity;
import com.hunlian.makelove.common.AppConfig;
import com.hunlian.makelove.common.ContextUtils;
import com.hunlian.makelove.common.StringUtil;
import com.hunlian.makelove.dialog.EducationSelectorDialog;
import com.hunlian.makelove.dialog.HeightSelectorDialog;
import com.hunlian.makelove.dialog.IncomeSelectorDialog;
import com.hunlian.makelove.net.HttpPostUploadUtil;
import com.hunlian.makelove.net.IServiceReturnProcess;
import com.hunlian.makelove.net.ServiceInterfaceDef;
import com.hunlian.makelove.tools.ACache;
import com.hunlian.makelove.tools.DeviceTools;
import com.hunlian.makelove.tools.MyToast;
import com.hunlian.makelove.tuyaimage.TuyaActivity;
import com.hunlian.makelove.view.CustomProgressDialog;
import com.hunlian.makelove.view.DatePickerDialogNew;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class OrganizingDataActivity extends BaseActivity implements ActivityCompat.OnRequestPermissionsResultCallback {

    private OrganizingDataActivity mSelf;
    private Button mBtnLogin, mBtnSave;
    private EditText mEtNickName, mEtJob, mEtCharacter,
            mEtInterest, mEtExpect, mEtIntroduce;
    private TextView mTvBirthday, mTvAddress, mTvHeight, mTvEducation, mTvIncome, mTvQQ;
    private SimpleDraweeView mIvHead, mIvEduCertificate, mIvIdCard;
    private ImageView mIvExampleEdu, mIvExampleIdCard;
    private ImageButton mIbAddress;
    private Spinner mSpIncome, mSpEducation;
    private RadioGroup mRgSex;
    private RadioButton mRbMale, mRbFemale;
    private RadioGroup mRgMarriage;
    private RadioButton mRbMarried, mRbUnmarried, mRbDivorced;
    private final int HeadCode = 1, EducationCode = 2, IDCode = 3, SHeadCode = 4, SEduCode = 5, SIDCode = 6;
    private final int HeadCodeCropper = 7,EduCodeCropper = 8,
            IDCodeCropper = 9,HeadCodeTuya = 10,EduCodeTuya = 11,IDCodeTuya = 12;
    private final int AddressCode = 100;
    private String StrHead = "head", StrEducation = "edu", StrID = "id";
    private TakeCameraOrAlbum mTakeCameraOrAlbum;
    private String mPicDir;
    private String mstrHeadPath, mstrEduPath, mstrIDPath;
    private String mStrSex;
    private CustomProgressDialog progressDialog;
    private HeightSelectorDialog mHeightSelectorDialog;
    private EducationSelectorDialog mEducationSelectorDialog;
    private IncomeSelectorDialog mIncomeSelectorDialog;
    private RelativeLayout mRlBirthday;
    private RelativeLayout mRlAddress;
    private RelativeLayout mRlHeight;
    private RelativeLayout mRlEdu;
    private RelativeLayout mRlIncome;
    private DatePickerDialogNew mPickerDialog;
    private String[] mIncomeArray, mEducationArray;
    private String mIncome, mEducation;
    private TableRow mTrEdu;
    private final int REQUEST_CODE_ASK_CAMERA = 8000;
    private final int REQUEST_EXTERNAL_STORAGE = 8001;
    private String mDirPath, mPicName;
    private int mRequestCode;
    private String bpath = "HLW_Pics/person";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mSelf = this;
        setContentView(R.layout.organizing_data_activity);

        ImageButton mIbBack = (ImageButton) findViewById(R.id.back);
        mIbBack.setVisibility(View.GONE);
        TextView mTvTitle = (TextView) findViewById(R.id.title);
        mTvTitle.setText("完善资料");
        findView();
        setListener();

        mRgSex.check(mRbMale.getId());
        mTakeCameraOrAlbum = new TakeCameraOrAlbum();
        //初始化照片信息
        mPicDir = ContextUtils.getPicDirName(this, bpath);

        //清理一些没用的对象，为本页留出足够的空间处理图片
        System.gc();

        initData();
    }

    private void findView() {

        mEtNickName = (EditText) findViewById(R.id.tv_nickname_value);
        mIvHead = (SimpleDraweeView) findViewById(R.id.iv_head);
        mRlBirthday = (RelativeLayout) findViewById(R.id.rl_birthday);
        mTvBirthday = (TextView) findViewById(R.id.tv_birthday_value);
        mRlAddress = (RelativeLayout) findViewById(R.id.rl_address);
        mRgSex = (RadioGroup) findViewById(R.id.rg);
        mRbMale = (RadioButton) findViewById(R.id.rb_male);
        mRbFemale = (RadioButton) findViewById(R.id.rb_female);
        mRgMarriage = (RadioGroup) findViewById(R.id.rg_marriage);
        mRbMarried = (RadioButton) findViewById(R.id.rb_married);
        mRbUnmarried = (RadioButton) findViewById(R.id.rb_unmarried);
        mRbDivorced = (RadioButton) findViewById(R.id.rb_divorced);
        mTvAddress = (TextView) findViewById(R.id.tv_address_value);
        mRlHeight = (RelativeLayout) findViewById(R.id.rl_height);
        mTvHeight = (TextView) findViewById(R.id.tv_height_value);
        mEtJob = (EditText) findViewById(R.id.tv_job_value);
        mSpIncome = (Spinner) findViewById(R.id.sp_income_value);
        mRlIncome = (RelativeLayout) findViewById(R.id.rl_income);
        mTvIncome = (TextView) findViewById(R.id.tv_income_value);
        mEtCharacter = (EditText) findViewById(R.id.tv_character_value);
        mEtInterest = (EditText) findViewById(R.id.tv_interest_value);
        mTvQQ = (TextView) findViewById(R.id.tv_qq_value);
        mSpEducation = (Spinner) findViewById(R.id.sp_education_value);
        mRlEdu = (RelativeLayout) findViewById(R.id.rl_edu);
        mTvEducation = (TextView) findViewById(R.id.tv_edu_value);
        mTrEdu = (TableRow) findViewById(R.id.tr_edu);
        mIvEduCertificate = (SimpleDraweeView) findViewById(R.id.iv_education_certificate);
        mIvIdCard = (SimpleDraweeView) findViewById(R.id.iv_id);
        mIvExampleEdu = (ImageView) findViewById(R.id.iv_edu_example);
        mIvExampleIdCard = (ImageView) findViewById(R.id.iv_id_example);
        mEtExpect = (EditText) findViewById(R.id.tv_expect_value);
        mEtIntroduce = (EditText) findViewById(R.id.tv_introduce_value);
        mBtnSave = (Button) findViewById(R.id.btn_save);

        mIncomeArray = getResources().getStringArray(R.array.income);
        ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        for (int i = 0; i < mIncomeArray.length; i++) {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("address", mIncomeArray[i]);
            list.add(map);
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, list,
                R.layout.income_spinner_item, new String[]{"address"},
                new int[]{R.id.tv_value});
        //设置显示的数据
        mSpIncome.setAdapter(simpleAdapter);


        mEducationArray = getResources().getStringArray(R.array.edu);
        ArrayList<HashMap<String, String>> educationList = new ArrayList<HashMap<String, String>>();
        for (int i = 0; i < mEducationArray.length; i++) {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("education", mEducationArray[i]);
            educationList.add(map);
        }
        SimpleAdapter eduAdapter = new SimpleAdapter(this, educationList,
                R.layout.income_spinner_item, new String[]{"education"},
                new int[]{R.id.tv_value});
        //设置显示的数据
        mSpEducation.setAdapter(eduAdapter);
    }

    private void setListener() {
        mRgSex.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == mRbMale.getId()) {
                    mStrSex = "男";
                } else {
                    mStrSex = "女";
                }
            }

        });

        mIvHead.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //dialog
                takePicDialog(mSelf, mPicDir, StrHead, HeadCode);
            }
        });

        mIvEduCertificate.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //dialog
                takePicDialog(mSelf, mPicDir, StrEducation, EducationCode);
            }
        });

        mIvIdCard.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //dialog
                takePicDialog(mSelf, mPicDir, StrID, IDCode);
            }
        });

        mRlBirthday.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mTvBirthday.getText().toString())) {
                    mPickerDialog = new DatePickerDialogNew(mSelf,
                            android.R.style.Theme_Holo_Light_Dialog_NoActionBar, 0, mHandler, "");
                } else {
                    mPickerDialog = new DatePickerDialogNew(mSelf,
                            android.R.style.Theme_Holo_Light_Dialog_NoActionBar, 0, mHandler, mTvBirthday.getText().toString());
                }
                mPickerDialog.show();
            }
        });

        mRlAddress.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(mSelf, WheelViewTimeActivity.class), AddressCode);
            }
        });

        mRlHeight.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mHeightSelectorDialog == null) {
                    mHeightSelectorDialog = new HeightSelectorDialog(mSelf,
                            android.R.style.Theme_Holo_Light_Dialog_NoActionBar, mHandler);
                }
                mHeightSelectorDialog.show();
            }
        });

        mRlEdu.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mEducationSelectorDialog == null) {
                    mEducationSelectorDialog = new EducationSelectorDialog(mSelf,
                            android.R.style.Theme_Holo_Light_Dialog_NoActionBar, mHandler, mEducationArray);
                }
                mEducationSelectorDialog.show();
            }
        });

        mRlIncome.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mIncomeSelectorDialog == null) {
                    mIncomeSelectorDialog = new IncomeSelectorDialog(mSelf,
                            android.R.style.Theme_Holo_Light_Dialog_NoActionBar, mHandler, mIncomeArray);
                }
                mIncomeSelectorDialog.show();
            }
        });

        mSpIncome.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                mIncome = mIncomeArray[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        mSpEducation.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                mEducation = mEducationArray[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        mIvExampleEdu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(mSelf, SpaceImageDetailActivity.class);
                intent.putExtra("url","res");
                intent.putExtra("resId",R.drawable.edu_example);
                startActivity(intent);
                overridePendingTransition(0, 0);
            }
        });
        mIvExampleIdCard.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(mSelf, SpaceImageDetailActivity.class);
                intent.putExtra("url","res");
                intent.putExtra("resId",R.drawable.sfz_example);
                startActivity(intent);
                overridePendingTransition(0, 0);
            }
        });

        mBtnSave.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Map<String, String> fileMap = new HashMap<String, String>();
                Map<String, String> textMap = new HashMap<String, String>();
                textMap.put("functionId", "HLW003");

                textMap.put("userId", AppConfig.getInstance().getLoginedUserId());
                String nickName = mEtNickName.getText().toString();
                if (StringUtil.isNotEmpty(nickName) == false) {
                    Toast.makeText(mSelf, "请输入昵称", Toast.LENGTH_SHORT).show();
                    return;
                }
                textMap.put("nickname", mEtNickName.getText().toString());

                if (StringUtil.isNotEmpty(mstrHeadPath) == false) {
                    Toast.makeText(mSelf, "请设置头像", Toast.LENGTH_SHORT).show();
                    return;
                }
                File fileHead = new File(mstrHeadPath);
                if (!fileHead.exists() || fileHead.length() == 0) {
                    Toast.makeText(mSelf, "请上传头像", Toast.LENGTH_SHORT).show();
                    return;
                }
                fileMap.put("pic", mstrHeadPath);

                String birthday = mTvBirthday.getText().toString();
                if (StringUtil.isNotEmpty(birthday) == false) {
                    Toast.makeText(mSelf, "请选择生日", Toast.LENGTH_SHORT).show();
                    return;
                }
                textMap.put("birthday", mTvBirthday.getText().toString());
                RadioButton rb = (RadioButton) findViewById(mRgSex.getCheckedRadioButtonId());
                if (rb == null) {
                    Toast.makeText(mSelf, "请选择性别", Toast.LENGTH_SHORT).show();
                    return;
                }
                textMap.put("sex", rb.getText().toString());
                String address = mTvAddress.getText().toString();
                if (StringUtil.isNotEmpty(address) == false) {
                    Toast.makeText(mSelf, "请选择现居住地", Toast.LENGTH_SHORT).show();
                    return;
                }
                textMap.put("address", mTvAddress.getText().toString());
                String height = mTvHeight.getText().toString();
                if (StringUtil.isNotEmpty(height) == false) {
                    Toast.makeText(mSelf, "请选择身高", Toast.LENGTH_SHORT).show();
                    return;
                }
                textMap.put("height", mTvHeight.getText().toString());

                String education = mTvEducation.getText().toString();
                if (StringUtil.isNotEmpty(education) == false) {
                    Toast.makeText(mSelf, "请选择学历", Toast.LENGTH_SHORT).show();
                    return;
                }
                textMap.put("education", mTvEducation.getText().toString());

                String job = mEtJob.getText().toString();
                if (StringUtil.isNotEmpty(job) == false) {
                    Toast.makeText(mSelf, "请填写职业", Toast.LENGTH_SHORT).show();
                    return;
                }
                textMap.put("job", mEtJob.getText().toString());
                String income = mTvIncome.getText().toString();
                if (StringUtil.isNotEmpty(income) == false) {
                    Toast.makeText(mSelf, "请选择收入", Toast.LENGTH_SHORT).show();
                    return;
                }
                textMap.put("income", mTvIncome.getText().toString());

                RadioButton rbMarriage = (RadioButton) findViewById(mRgMarriage.getCheckedRadioButtonId());
                if (rbMarriage == null) {
                    Toast.makeText(mSelf, "请选择婚姻状况", Toast.LENGTH_SHORT).show();
                    return;
                }
                textMap.put("hunyin", rbMarriage.getText().toString());

                String character = mEtCharacter.getText().toString();
                if (StringUtil.isNotEmpty(character) == false) {
                    Toast.makeText(mSelf, "请填写性格", Toast.LENGTH_SHORT).show();
                    return;
                }
                textMap.put("character", mEtCharacter.getText().toString());

                String interest = mEtInterest.getText().toString();
                if (StringUtil.isNotEmpty(interest) == false) {
                    Toast.makeText(mSelf, "请填写兴趣爱好", Toast.LENGTH_SHORT).show();
                    return;
                }
                textMap.put("hobby", mEtInterest.getText().toString());

                String qq = mTvQQ.getText().toString();
                if (StringUtil.isNotEmpty(qq) == false) {
                    Toast.makeText(mSelf, "请填写QQ", Toast.LENGTH_SHORT).show();
                    return;
                }
                textMap.put("qq", mTvQQ.getText().toString());

                String introduce = mEtIntroduce.getText().toString();
                if (StringUtil.isNotEmpty(introduce) == false) {
                    Toast.makeText(mSelf, "请填写补充内容", Toast.LENGTH_SHORT).show();
                    return;
                }
                textMap.put("intro", mEtIntroduce.getText().toString());

                String expect = mEtExpect.getText().toString();
                if (StringUtil.isNotEmpty(expect) == false) {
                    Toast.makeText(mSelf, "请填写期望对方", Toast.LENGTH_SHORT).show();
                    return;
                }
                textMap.put("expect", mEtExpect.getText().toString());

                if (StringUtil.isNotEmpty(mstrIDPath) == false) {
                    Toast.makeText(mSelf, "请上传身份证照片", Toast.LENGTH_SHORT).show();
                    return;
                }
                File fileID = new File(mstrIDPath);
                if (!fileID.exists() || fileID.length() == 0) {
                    Toast.makeText(mSelf, "请上传身份证照片", Toast.LENGTH_SHORT).show();
                    return;
                }
                fileMap.put("identity", mstrIDPath);

                if (mTrEdu.getVisibility() != View.GONE) {
                    if (StringUtil.isNotEmpty(mstrEduPath) == false) {
                        Toast.makeText(mSelf, "请上传学历证照片", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    File fileEdu = new File(mstrEduPath);
                    if (!fileEdu.exists() || fileEdu.length() == 0) {
                        Toast.makeText(mSelf, "请上传学历证照片", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    fileMap.put("education_pic", mstrEduPath);
                }


                //System.out.println("mstrHeadPath："+mstrHeadPath);
                //System.out.println("mstrEduPath："+mstrEduPath);
                //System.out.println("mstrIDPath："+mstrIDPath);
                //String ret = mHttpPostUploadUtil.formUpload(urlStr, textMap, fileMap);
                //System.out.println("上传完成："+ret);

                if (!AppApplication.networkAvailable) {
                    MyToast.showShort("没有网络");
                    return;
                }
                progressDialog = CustomProgressDialog.createDialog(mSelf, "正在加载中...");
                progressDialog.show();

                HttpPostUploadUtil.doPost(ServiceInterfaceDef.SERVICE_URL, textMap, fileMap,
                        new IServiceReturnProcess() {
                            @Override
                            public void process(String serviceReturn) {
                                if (progressDialog != null && progressDialog.isShowing()) {
                                    try {
                                        progressDialog.dismiss();
                                        progressDialog = null;
                                    } catch (Exception e) {
                                    }
                                }
                                //Printout.println("完善资料反馈 :" + serviceReturn);
                                try {
                                    JSONObject obj = new JSONObject(serviceReturn);
                                    if (null == obj) {
                                        Toast.makeText(mSelf, "请求失败", Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                    String status = obj.getString("status");
                                    if ("1".equals(status)) {
                                        //Printout.println("完善资料反馈成功" + serviceReturn);
                                        //清楚完善资料缓存
                                        ACache.get(OrganizingDataActivity.this.getApplication()).put(AppConfig.getInstance().getLoginedUserId(),new OrganizingDataBean());

                                        Toast.makeText(mSelf,
                                                "保存成功", Toast.LENGTH_SHORT)
                                                .show();
                                        AppConfig.getInstance().setBooleanValue("organizingData" + AppConfig.getInstance().getLoginedUserId(), true);
                                        startActivity(new Intent(mSelf, MainActivity.class));
                                        mSelf.finish();
                                    } else {
                                        //清楚userId
                                        AppConfig.getInstance().clearLoginedUserId();
                                        String message = obj.getString("message");
                                        Toast.makeText(mSelf, message, Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    Toast.makeText(mSelf, "请求失败", Toast.LENGTH_SHORT).show();
                                }

                            }
                        }
                );
            }
        });
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String date = msg.getData().getString("date");
                    dateSet(msg.what, date);
                    if (mPickerDialog != null) {
                        mPickerDialog.dismiss();
                    }
                    break;
                case HeightSelectorDialog.VALUE:
                    String height = msg.getData().getString("height");
                    mTvHeight.setText(height);
                    break;
                case EducationSelectorDialog.Edu_VALUE:
                    String edu = msg.getData().getString("edu");
                    mTvEducation.setText(edu);
                    if ("初中及以下".equals(edu) || "中专或者高中".equals(edu)) {
                        mTrEdu.setVisibility(View.GONE);
                    } else {
                        //mTrEdu.setVisibility(View.VISIBLE);//不再显示学历
                    }
                    break;
                case IncomeSelectorDialog.Income_VALUE:
                    String income = msg.getData().getString("income");
                    mTvIncome.setText(income);
                    break;
                default:
                    break;
            }
        }

        ;
    };

    private void dateSet(int what, String date) {
        if (what == 1) {
            long dateTag = DeviceTools.getYearMonthDayNum(date);
            if (dateTag > DeviceTools.getYearMothDayNum()) {
                // txtP2pInvestDate.setText(DeviceTools.getYearMonthDay());
                Toast.makeText(mSelf, "出生日期不能大于当前日期", Toast.LENGTH_SHORT);
            } else {
                mTvBirthday.setText(date);
            }
        }
    }

    /**
     * 拍照、从相册选择、预览
     *
     * @param activity
     * @param dirPath
     * @param picName
     * @param requestCode
     * @author: zj
     * @time: 2013-11-1上午10:20:28
     */
    public void takePicDialog(final Activity activity, final String dirPath, final String picName, final int requestCode) {

        mDirPath = dirPath;
        mPicName = picName;
        mRequestCode = requestCode;

        //此处直接new一个Dialog对象出来，在实例化的时候传入主题
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        Context mContext = getApplicationContext();
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.dialog_pic_whole,

                (ViewGroup) findViewById(R.id.dialog_whole_ll1));

        Button photoAlbum = (Button) layout.findViewById(R.id.dialog_pic_whole_select_from_album);
        Button takePic = (Button) layout.findViewById(R.id.dialog_pic_whole_select_take_pic);
        Button preview = (Button) layout.findViewById(R.id.dialog_pic_whole_preview);
        Button cancel = (Button) layout.findViewById(R.id.dialog_pic_whole_cancel);

        builder.setView(layout);

        final AlertDialog alertDialog = builder.create();
        alertDialog.show();

        takePic.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                //动态申请权限
                int checkCameraPermission = ContextCompat.checkSelfPermission(OrganizingDataActivity.this, Manifest.permission.CAMERA);
                if (checkCameraPermission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(OrganizingDataActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            REQUEST_CODE_ASK_CAMERA);
                    return;
                }

                if (requestCode == HeadCode) {
                    //调用系统相机
                    mstrHeadPath = mTakeCameraOrAlbum.takePics(activity, dirPath, picName, requestCode);
                } else if (requestCode == EducationCode) {
                    //调用系统相机
                    mstrEduPath = mTakeCameraOrAlbum.takePics(activity, dirPath, picName, requestCode);
                } else if (requestCode == IDCode) {
                    //调用系统相机
                    mstrIDPath = mTakeCameraOrAlbum.takePics(activity, dirPath, picName, requestCode);
                }

                alertDialog.dismiss();
            }

        });


        photoAlbum.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                //动态申请权限
                int checkCameraPermission = ContextCompat.checkSelfPermission(OrganizingDataActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (checkCameraPermission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(OrganizingDataActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            REQUEST_EXTERNAL_STORAGE);
                    return;
                }

                if (requestCode == HeadCode) {
                    //调用系统相册
                    mTakeCameraOrAlbum.takeSysPhotoAlbum(activity, SHeadCode);
                } else if (requestCode == EducationCode) {
                    //调用系统相册
                    mTakeCameraOrAlbum.takeSysPhotoAlbum(activity, SEduCode);
                } else if (requestCode == IDCode) {
                    //调用系统相册
                    mTakeCameraOrAlbum.takeSysPhotoAlbum(activity, SIDCode);
                }

                alertDialog.dismiss();
            }

        });

        preview.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (requestCode == HeadCode) {
                    if (null == mstrHeadPath || mstrHeadPath.equals("")) {
                        Toast.makeText(activity, "请先拍照或选择照片再预览", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //预览照片
                    preViewPhoto(mstrHeadPath);
                } else if (requestCode == EducationCode) {
                    if (null == mstrEduPath || mstrEduPath.equals("")) {
                        Toast.makeText(activity, "请先拍照或选择照片再预览", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //预览照片
                    preViewPhoto(mstrEduPath);
                } else if (requestCode == IDCode) {
                    if (null == mstrIDPath || mstrIDPath.equals("")) {
                        Toast.makeText(activity, "请先拍照或选择照片再预览", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //预览照片
                    preViewPhoto(mstrIDPath);
                }
                alertDialog.dismiss();

            }

        });

        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //取消
                alertDialog.dismiss();
            }

        });

    }

    private void preViewPhoto(String path){
        Intent intent = new Intent(mSelf, SpaceImageDetailActivity.class);
        intent.putExtra("url",path);
        startActivity(intent);
        overridePendingTransition(0, 0);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    takePicDialog(OrganizingDataActivity.this, mDirPath, mPicName, mRequestCode);
                } else {
                    // Permission Denied
                    Toast.makeText(OrganizingDataActivity.this, "拍照授权被拒", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            case REQUEST_EXTERNAL_STORAGE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    takePicDialog(OrganizingDataActivity.this, mDirPath, mPicName, mRequestCode);
                } else {
                    // Permission Denied
                    Toast.makeText(OrganizingDataActivity.this, "从相册选择图片授权被拒", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == HeadCode && resultCode == Activity.RESULT_OK) {//拍照
            //旋转保存图片
            boolean boo = mTakeCameraOrAlbum.handlePic(mSelf, mstrHeadPath);
            if(!boo){
                Toast.makeText(mSelf,"保存图片失败",Toast.LENGTH_SHORT).show();
            }
            //编辑图片
            startCropperActivity(HeadCodeCropper, mstrHeadPath,mPicDir+StrHead+".jpg");
        } else if (requestCode == EducationCode && resultCode == Activity.RESULT_OK) {//拍照
            //旋转保存图片
            mTakeCameraOrAlbum.handlePic(mSelf, mstrEduPath);
            //编辑图片
            startTuyaActivity(EduCodeTuya, mstrEduPath,mPicDir+StrEducation+".jpg");
        } else if (requestCode == IDCode && resultCode == Activity.RESULT_OK) {    //拍照
            //旋转保存图片
            mTakeCameraOrAlbum.handlePic(mSelf, mstrIDPath);
            //编辑图片
            startTuyaActivity(IDCodeTuya, mstrIDPath,mPicDir+StrID+".jpg");
        } else if (requestCode == SHeadCode && resultCode == Activity.RESULT_OK) {
            //处理从系统相册选择图片
            mstrHeadPath = mTakeCameraOrAlbum.handleSelectedSysPhoto(mSelf,data);
            if(TextUtils.isEmpty(mstrHeadPath)){
                return;
            }
            //编辑图片
            startCropperActivity(HeadCodeCropper, mstrHeadPath,mPicDir+StrHead+".jpg");
        } else if (requestCode == SEduCode && resultCode == Activity.RESULT_OK) {
            //处理从系统相册选择图片
            mstrEduPath = mTakeCameraOrAlbum.handleSelectedSysPhoto(mSelf,data);

            File file = new File(mstrEduPath);
            if (!file.exists() || file.length() == 0) {
                Toast.makeText(mSelf, "请重新上传学历证照片", Toast.LENGTH_SHORT).show();
                return;
            }
            //编辑图片
            startTuyaActivity(EduCodeTuya, mstrEduPath,mPicDir+StrEducation+".jpg");
        } else if (requestCode == SIDCode && resultCode == Activity.RESULT_OK) {
            //处理从系统相册选择图片
            mstrIDPath = mTakeCameraOrAlbum.handleSelectedSysPhoto(mSelf,data);

            File file = new File(mstrIDPath);
            if (!file.exists() || file.length() == 0) {
                Toast.makeText(mSelf, "请重新上传身份证照片", Toast.LENGTH_SHORT).show();
                return;
            }
            //编辑图片
            startTuyaActivity(IDCodeTuya, mstrIDPath,mPicDir+StrID+".jpg");
        } else if (requestCode == HeadCodeCropper && resultCode == RESULT_OK) {
            mstrHeadPath = mPicDir+StrHead+".jpg";
            //加载并显示图片
            Fresco.getImagePipeline().evictFromCache(Uri.parse("file://"+mstrHeadPath));
            mIvHead.setImageURI(Uri.parse("file://"+mstrHeadPath));
        }else if (requestCode == EduCodeTuya && resultCode == RESULT_OK) {
            mstrEduPath = mPicDir+StrEducation+".jpg";
            //加载并显示图片
            Fresco.getImagePipeline().evictFromCache(Uri.parse("file://"+mstrEduPath));
            mIvEduCertificate.setImageURI(Uri.parse("file://"+mstrEduPath));
        } else if (requestCode == IDCodeTuya && resultCode == RESULT_OK) {
            mstrIDPath = mPicDir+StrID+".jpg";
            //加载并显示图片
            Fresco.getImagePipeline().evictFromCache(Uri.parse("file://"+mstrIDPath));
            mIvIdCard.setImageURI("file://"+Uri.parse(mstrIDPath));
        } else if (requestCode == AddressCode && resultCode == WheelViewTimeActivity.RESULT_SUCCESS) {
            if (null != data) {
                mTvAddress.setText(data.getStringExtra("address"));
            }
        }
        //super.onActivityResult(requestCode, resultCode, data);
    }

    private void deletePic(String picPath){
        if(TextUtils.isEmpty(picPath)){
            return;
        }
        //删除图片
        ContextUtils.DeleteFile(new File(picPath));
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(picPath))));
    }

    private void startCropperActivity(int requestCode, String picPath,String savePath) {
        //编辑图片
        //Intent intent = new Intent(mSelf,CropperActivity.class);
        Intent intent = new Intent(mSelf, ClipImageActivity.class);
        intent.putExtra("path", picPath);
        intent.putExtra("savePath", savePath);
        mSelf.startActivityForResult(intent, requestCode);
    }

    private void startTuyaActivity(int requestCode, String picPath,String savePath) {
        //编辑图片
        Intent intent = new Intent(mSelf, TuyaActivity.class);
        intent.putExtra("path", picPath);
        intent.putExtra("savePath", savePath);
        mSelf.startActivityForResult(intent, requestCode);
    }

    private long mExitTime;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (event.getKeyCode()) {
                case KeyEvent.KEYCODE_BACK:

                    if ((System.currentTimeMillis() - mExitTime) > 2000) {
                        Toast.makeText(mSelf, "再按一次退出婚恋网",
                                Toast.LENGTH_SHORT).show();
                        mExitTime = System.currentTimeMillis();
                    } else {
                        checkAndSave(false);
                        AppConfig.setUserToken("");
                        AppConfig.source = "";
                        AppConfig.userName = "";
                        AppConfig.getInstance().setStringValue("userId", "");
                        AppConfig.openId = "";
                        mSelf.finish();
                    }
                    return true;

            }
        }

        return super.dispatchKeyEvent(event);
    }

    private void initData(){
        String userIdLogin = AppConfig.getInstance().getLoginedUserId();
        OrganizingDataBean organizingDataBean = (OrganizingDataBean)ACache.get(this.getApplication()).getAsObject(userIdLogin);
        if(organizingDataBean!=null){
            String userId = organizingDataBean.getUserId();
            if(TextUtils.isEmpty(userId)){
                return;
            }
            if(!userId.equals(AppConfig.getInstance().getLoginedUserId())){
                return;
            }
            String nickName = organizingDataBean.getNickname();
            String headPicPath = organizingDataBean.getHeadPicPath();
            String birthday = organizingDataBean.getBirthday();
            String sex = organizingDataBean.getSex();
            String address = organizingDataBean.getAddress();
            String height = organizingDataBean.getHeight();
            String education = organizingDataBean.getEducation();
            String job = organizingDataBean.getJob();
            String income = organizingDataBean.getIncome();
            String hunyin = organizingDataBean.getHunyin();
            String character = organizingDataBean.getCharacter();
            String hobby = organizingDataBean.getHobby();
            String qq = organizingDataBean.getQq();
            String intro = organizingDataBean.getIntro();
            String expect = organizingDataBean.getExpect();
            String identityPicPath = organizingDataBean.getIdentityPicPath();
            String educationPicPath = organizingDataBean.getEducationPicPath();

            mEtNickName.setText(nickName);
            //加载并显示图片
            if(!TextUtils.isEmpty(headPicPath)) {
                mstrHeadPath = headPicPath;
                mTakeCameraOrAlbum.loadShowIdentity(mSelf, mIvHead, headPicPath, true);
            }
            mTvBirthday.setText(birthday);
            if(!TextUtils.isEmpty(sex)){
                if("男".equals(sex)){
                    mRbMale.setChecked(true);
                }else if("女".equals(sex)){
                    mRbFemale.setChecked(true);
                }
            }
            mTvAddress.setText(address);
            mTvHeight.setText(height);
            mTvEducation.setText(education);
            mEtJob.setText(job);
            mTvIncome.setText(income);
            if(!TextUtils.isEmpty(hunyin)){
                if("已婚".equals(hunyin)){
                    mRbMarried.setChecked(true);
                }else if("未婚".equals(hunyin)){
                    mRbUnmarried.setChecked(true);
                }else if("离异".equals(hunyin)){
                    mRbDivorced.setChecked(true);
                }
            }
            mEtCharacter.setText(character);
            mEtInterest.setText(hobby);
            mTvQQ.setText(qq);
            //加载并显示图片
            if(!TextUtils.isEmpty(identityPicPath)) {
                mstrIDPath = identityPicPath;
                //mTakeCameraOrAlbum.loadShowIdentity(mSelf, mIvIdCard, identityPicPath, false);
                mIvIdCard.setImageURI(Uri.parse(identityPicPath));
            }
            if(!TextUtils.isEmpty(educationPicPath)) {
                mstrEduPath = educationPicPath;
                //mTakeCameraOrAlbum.loadShowIdentity(mSelf, mIvEduCertificate, educationPicPath, true);
                mIvEduCertificate.setImageURI(Uri.parse(educationPicPath));
            }
            mEtIntroduce.setText(intro);
            mEtExpect.setText(expect);

        }
    }

    private void checkAndSave(boolean check){
        OrganizingDataBean organizingDataBean = new OrganizingDataBean();
        organizingDataBean.setUserId(AppConfig.getInstance().getLoginedUserId());
        String nickName = mEtNickName.getText().toString();
        if (check&&StringUtil.isEmpty(nickName)) {
            Toast.makeText(mSelf, "请输入昵称", Toast.LENGTH_SHORT).show();
            return;
        }
        organizingDataBean.setNickname(mEtNickName.getText().toString());

        if(check) {
            if (StringUtil.isEmpty(mstrHeadPath)) {
                Toast.makeText(mSelf, "请设置头像", Toast.LENGTH_SHORT).show();
                return;
            }

            File fileHead = new File(mstrHeadPath);
            if (!fileHead.exists() || fileHead.length() == 0) {
                Toast.makeText(mSelf, "请上传头像", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        organizingDataBean.setHeadPicPath(mstrHeadPath);

        String birthday = mTvBirthday.getText().toString();
        if (check&&StringUtil.isEmpty(birthday)) {
            Toast.makeText(mSelf, "请选择生日", Toast.LENGTH_SHORT).show();
            return;
        }
        organizingDataBean.setBirthday(mTvBirthday.getText().toString());

        RadioButton rb = (RadioButton) findViewById(mRgSex.getCheckedRadioButtonId());
        if (check&&rb == null) {
            Toast.makeText(mSelf, "请选择性别", Toast.LENGTH_SHORT).show();
            return;
        }
        organizingDataBean.setSex(rb.getText().toString());

        String address = mTvAddress.getText().toString();
        if (check&&StringUtil.isEmpty(address)) {
            Toast.makeText(mSelf, "请选择现居住地", Toast.LENGTH_SHORT).show();
            return;
        }
        organizingDataBean.setAddress(mTvAddress.getText().toString());

        String height = mTvHeight.getText().toString();
        if (check&&StringUtil.isEmpty(height)) {
            Toast.makeText(mSelf, "请选择身高", Toast.LENGTH_SHORT).show();
            return;
        }
        organizingDataBean.setHeight(mTvHeight.getText().toString());

        String education = mTvEducation.getText().toString();
        if (check&&StringUtil.isEmpty(education)) {
            Toast.makeText(mSelf, "请选择学历", Toast.LENGTH_SHORT).show();
            return;
        }
        organizingDataBean.setEducation(mTvEducation.getText().toString());

        String job = mEtJob.getText().toString();
        if (check&&StringUtil.isEmpty(job)) {
            Toast.makeText(mSelf, "请填写职业", Toast.LENGTH_SHORT).show();
            return;
        }
        organizingDataBean.setJob(mEtJob.getText().toString());

        String income = mTvIncome.getText().toString();
        if (check&&StringUtil.isNotEmpty(income)) {
            Toast.makeText(mSelf, "请选择收入", Toast.LENGTH_SHORT).show();
            return;
        }
        organizingDataBean.setIncome(mTvIncome.getText().toString());

        RadioButton rbMarriage = (RadioButton) findViewById(mRgMarriage.getCheckedRadioButtonId());

        if (rbMarriage == null) {
            if(check){
                Toast.makeText(mSelf, "请选择婚姻状况", Toast.LENGTH_SHORT).show();
                return;
            }
        }else {
            organizingDataBean.setHunyin(rbMarriage.getText().toString());
        }

        String character = mEtCharacter.getText().toString();
        if (check&&StringUtil.isEmpty(character)) {
            Toast.makeText(mSelf, "请填写性格", Toast.LENGTH_SHORT).show();
            return;
        }
        organizingDataBean.setCharacter(mEtCharacter.getText().toString());

        String interest = mEtInterest.getText().toString();
        if (check&&StringUtil.isEmpty(interest)) {
            Toast.makeText(mSelf, "请填写兴趣爱好", Toast.LENGTH_SHORT).show();
            return;
        }
        organizingDataBean.setHobby(mEtInterest.getText().toString());

        String qq = mTvQQ.getText().toString();
        if (check&&StringUtil.isEmpty(qq)) {
            Toast.makeText(mSelf, "请填写QQ", Toast.LENGTH_SHORT).show();
            return;
        }
        organizingDataBean.setQq(mTvQQ.getText().toString());

        String introduce = mEtIntroduce.getText().toString();
        if (check&&StringUtil.isEmpty(introduce)) {
            Toast.makeText(mSelf, "请填写补充内容", Toast.LENGTH_SHORT).show();
            return;
        }
        organizingDataBean.setIntro(mEtIntroduce.getText().toString());

        String expect = mEtExpect.getText().toString();
        if (check&&StringUtil.isEmpty(expect)) {
            Toast.makeText(mSelf, "请填写期望对方", Toast.LENGTH_SHORT).show();
            return;
        }
        organizingDataBean.setExpect(mEtExpect.getText().toString());

        if(check) {
            if (StringUtil.isEmpty(mstrIDPath)) {
                Toast.makeText(mSelf, "请上传身份证照片", Toast.LENGTH_SHORT).show();
                return;
            }
            File fileID = new File(mstrIDPath);
            if (!fileID.exists() || fileID.length() == 0) {
                Toast.makeText(mSelf, "请上传身份证照片", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        organizingDataBean.setIdentityPicPath(mstrIDPath);

        if (mTrEdu.getVisibility() != View.GONE) {
            if(check) {
                if (StringUtil.isEmpty(mstrEduPath)) {
                    Toast.makeText(mSelf, "请上传学历证照片", Toast.LENGTH_SHORT).show();
                    return;
                }
                File fileEdu = new File(mstrEduPath);
                if (!fileEdu.exists() || fileEdu.length() == 0) {
                    Toast.makeText(mSelf, "请上传学历证照片", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            organizingDataBean.setEducationPicPath(mstrEduPath);
        }

        ACache.get(this.getApplication()).put(AppConfig.getInstance().getLoginedUserId(),organizingDataBean);
    }

}
